<template>
  <div ref="asideleft" id="asideleft">


    <div class="aside-left">
      <div class="isscroll">
        <el-scrollbar style="height:100%;" ref="scrollbar" id="scrollbar">
          <ul class="list-box">
            <li class="title-list" v-for="(item,index) in folderList" @click="handleSelectClick(index, item.folderId)">
              <a :class="{select:item.folderId == folderId}" class="clearfix" :title="item.folderName">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-folder"></use>
                </svg>
                <span class="title-content" :title="item.folderName">{{item.folderName}}</span>
                <span class="title-num" v-if="item.folderId!==-100">({{item.count}})</span>
                <!--编辑菜单按钮-->
                <svg v-if="forbiddenFolderIds.indexOf(item.folderId)==-1"
                     class="icon icon-settings" :data-class="index" :class="{iconblock:item.folderId == folderId}"
                     aria-hidden="true"
                     @click="handleSettingClick(index)">
                  <use xlink:href="#icon-settings"></use>
                </svg>
              </a>
              <div class='tag-box tag-art-list' :class="{selectIcon:_showEditMenu(item.folderId)}">
                <ul>
                  <li class="list">
                    <el-button type="text" @click="handleRename(index, item.folderId)">重命名</el-button>
                  </li>
                  <li class="list" @click="deleteFolder(index,item.folderId)">删除目录</li>
                </ul>
              </div>
            </li>
          </ul>
          <div class="new-folder" v-show="!showFolderInput" @click="handleAddClick()">
            新建文件夹
          </div>

          <div class="new-name" v-show="showFolderInput">
            <span><em>{{editFolderNameLength}}</em>/20</span>
            <input class="self-input" placeholder="请输入文件夹名字" v-model="editfolderName" maxlength="20"
                   @keyup.enter="makesureFoldername()"/>
            <button class="save-btn-two" @click="makesureFoldername()">确定</button>
            <button class="cancel-btn" @click="_resetEditFolderState()">取消</button>
          </div>
        </el-scrollbar>
      </div>
      <div class="takeup" id="takeup">
				<span @click="handleTakeup">
					<svg class="icon" aria-hidden="true">
					  	<use xlink:href="#icon-burger"></use>
					</svg>
				</span>

        <p>收起边栏</p>
      </div>

    </div>


    <el-dialog title="重命名文件夹" :visible.sync="showRenameEditPanel" width="30%" center custom-class="self-dialog">
      <div class="new-name new-name-modal">
        <span><em>{{editFolderNameLength}}</em>/20</span>
        <input class="self-input large-input" placeholder="请输入文件夹名字" v-model="editfolderName" maxlength="20"
               @keyup.enter="makesureRename()"/>
      </div>
      <span slot="footer" class="dialog-footer">
			    <el-button @click="_resetEditFolderState()">取 消</el-button>
			    <el-button type="primary" @click="makesureRename()">确 定</el-button>
		 	</span>
    </el-dialog>
  </div>
</template>

<script>
  import {mapState, mapActions} from 'vuex';
  import util from '@/lib/util';

  export default {
    name: 'AsideLeft',
    props: ["height"],
    components: {},
    data() {
      return {
        forbiddenFolderIds: [-100],//禁止编辑的目录id，-100 最近编辑  我的写稿箱（每个用户id不一样）
        showMenu: false,//控制重命名菜单是否显示
        showFolderInput: false,//控制新建文件夹编辑框是否展示
        editFolderNameLength: 0,//编辑文件夹输入值长度（新建或重命名）
        editfolderName: '',//编辑文件夹名称（新建或重命名）
        showRenameEditPanel: false//控制重命名文件夹编辑框是否显示
      }
    },
    created() {

    },
    mounted: function () {
      // 请求文件夹列表 folderId为1,默认显示为第一个
      let that = this;
      this.fetchFolderList().then((res) => {
        if (res.code == 1) {
          let list = res.data || [];
          list.forEach((item, index) => {
            if (item.folderName === "我的写稿箱") {

              that.forbiddenFolderIds.push(item.folderId);
              return;
            }
          })

        }
      });
    },
    computed: {
      ...mapState([
        'folderList',
        'folderId',
        'articleList',
        'searchState'
      ]),
    },
    watch: {
      //编辑的文章名称
      editfolderName(curVal, oldVal) {
        this.editFolderNameLength = curVal.length;
        if (curVal.length > 20) {
          this.editfolderName = curVal.slice(0, 20)
        }
      }

    },
    methods: {
      ...mapActions([
        'fetchFolderList',
        'insertFolder',
        'changeFolderid',
        'changeFolderArticleCount'

      ]),
      //判断是否需要显示重命名菜单
      _showEditMenu(curFolderId) {
        return curFolderId === this.folderId && this.forbiddenFolderIds.indexOf(curFolderId) == -1 && this.showMenu;
      },
      _resetEditFolderState() {
        //初始化状态数据
        this.editfolderName = '';
        //关闭编辑面盘
        this.showFolderInput = false;
        //关闭重命名面盘
        this.showRenameEditPanel = false;
      },
      //删除之后计算出下一个选中的文件夹id
      _delNextSelect(delFolderId) {
        let list = this.folderList || [];
        let nextFolderId = -1;
        list.forEach((item, index) => {
          if (item.folderId == delFolderId) {
            if (index == 0) {
              //删除的是头则下一个就是当前列表中的第二个
              nextFolderId = list[1].folderId;
            } else if (index == list.length - 1) {
              //删除的是尾，则下一个就是当前列表中的倒是第二个
              nextFolderId = list[list.length - 2].folderId;
            }
            else {
              //删除的是中间则是当前列表中的下一个
              nextFolderId = list[index + 1].folderId;
            }
          }
        });
        return nextFolderId;
      },
      //新建文件夹确定按钮事件
      makesureFoldername() {
        let that = this;
        if (!this.editfolderName.trim()) {
          this.$message.error('请输入文件夹名称');
          return;
        }

        let pass = true;
        this.folderList.forEach((item, index) => {
          if (item.folderName.trim() === that.editfolderName.trim()) {
            this.$message.error("已存在重名文件夹");
            pass = false;
            return;
          }
        });
        if (!pass) {
          return;
        }

        this.insertFolder({'name': this.editfolderName.trim()}).then((res) => {
          // 错误处理
          if (res.code !== 1) {
            this.$message.error(res.msg)
          } else {
            //返回的文件夹对象没有count属性，手动增加上
            res.data["count"] = 0;
          }
          //初始化状态数据
          this._resetEditFolderState();
          //刷新文件夹列表
          this.fetchFolderList().then((listres) => {
            //刷新之后自动选中新增加的文件夹
            that.handleSelectClick(0, res.data.folderId);
          });
        });

      },
      //重命名目录提交
      makesureRename() {
        let that = this;
        let pass = true;

        if (!this.editfolderName.trim()) {
          this.$message.error('请输入文件夹名称');
          return;
        }

        this.folderList.forEach((item, index) => {
          if (item.folderName.trim() === that.editfolderName.trim()) {
            if (item.folderId !== that.folderId) {
              this.$message.error("已存在重名文件夹");
              pass = false;
              return;
            }
            else {
              that._resetEditFolderState();
              pass = false;
              return;
            }
          }
        });
        if (!pass) {
          return;
        }
        let param = {
          'id': this.folderId,
          'name': this.editfolderName.trim()
        };
        util.ajax.post('/folder/update', {
          ...param
        }).then((res) => {
          // 修改成功后重置状态和刷新文件夹列表
          if (res.code == 1) {

            that._resetEditFolderState();
            //刷新文件夹列表
            that.fetchFolderList({folderId: that.folderId}).then((listres) => {
              //刷新之后自动选中新增加的文件夹
              that.handleSelectClick(0, that.folderId);
            });
          }
        });
      },

      //点击重命名按钮处理事件
      handleRename(index, folderid) {
        this._resetEditFolderState();
        this.showRenameEditPanel = true;
      },

      //删除文件夹
      deleteFolder(index, folderid) {
        if ((this.articleList || []).length > 0) {
          this.$message.warning("抱歉，此目录中尚有文章，请清空后再删除。");
          return;
        }
        let that = this;
        let param = {
          'id': folderid
        };

        let nextFolderID = that._delNextSelect(folderid);
        util.ajax.post('/folder/del', {
          ...param
        }).then((res) => {
          if (res.code == 1) {
            //刷新文件夹列表
            that.fetchFolderList().then((listres) => {
              //刷新之后自动选中新增加的文件夹
              that.handleSelectClick(0, nextFolderID);
            });
          }
        });
        //this.$confirm("确定删除吗？").then(_ => {}).catch(_ => {});
      },

      //处理文件夹选中事件
      handleSelectClick(index, folderId) {

        // 避免重复请求
        if (folderId == this.folderId) {
          return
        }
        // 选中之后改变全局变量当前的选中文件夹id
        this.changeFolderid(folderId);
        //重置显示菜单的按钮
        this.showMenu = false;
      },

      //处理新建文件夹按钮点击事件
      handleAddClick() {
        let bar = this.$refs.scrollbar;

        this.showFolderInput = true;
        this.$nextTick(() => {
          //将滚动条自动滚动到底部
          bar.wrap.scrollTop += 200;
        });


      },

      //点击重命名菜单按钮点击事件
      handleSettingClick() {
        this.showMenu = !this.showMenu;
      },

      //收起边栏
      handleTakeup() {
        var asideRight = document.getElementById("asideRight");
        var asidecenter = document.getElementById("asidecenter");
        var takeup = document.getElementById("takeup");
        var open = document.getElementById("open");
        takeup.style.display = 'none';
        open.style.display = 'block';
        asidecenter.style.left = '0px';
        asideRight.style.left = '302px';
        this.$refs.asideleft.style.display = 'none'
      }

    }
  }
</script>

<style lang="scss" scoped>
  @import "@/assets/css/style.scss";

  .edit-column {
    flex-direction: column;
  }

  .aside-left {
    display: flex;
    flex-direction: column;
    position: absolute;
    top: 83px;
    left: 0px;
    bottom: 0px;
    width: 220px;
    overflow: hidden;
    border-right: 1px solid $listborderColor;
    .isscroll {
      margin-right: -17px;
      /*width:100%;*/
      height: 100%;
      margin-bottom: 100px;
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
    }
    .list-box {
      width: 220px;
      .title-list {
        position: relative;
        border-bottom: 1px solid $borderbottomColor;
        line-height: 60px;
        height: 60px;
        cursor: pointer;
        &:hover {
          background: $listBgColor;
        }
        a {
          position: relative;
          padding: 0px 18px;
          display: block;
          font-size: $fs14;
          color: $listTitleColor;
          span {
            float: left;
          }
          .title-content {
            position: relative;
            margin-right: 5px;
            display: inline-block;
            max-width: 100px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .icon {
            margin: 20px 20px 0px 0px;
            float: left;
            vertical-align: middle;
            width: 20px;
            height: 20px;
            color: $vfConcentColor;
          }
          .icon-settings {
            margin: 0px;
            position: absolute;
            top: 20px;
            right: 16.6px;
            display: none;
          }
          .iconblock {
            display: block !important;
            color: $vfConcentColor !important;
          }
        }
        .selectIcon {
          display: block !important;
        }
        .tag-box {
          display: none;
          position: absolute;
          top: 50px;
          right: 5px;
          z-index: 999;
          text-align: center;
          background: #fff;
          font-size: $fs16;
          border: 1px solid $listborderColor;
          border-radius: 10px;
          color: $vfConcentColor;
          &:after,
          &:before {
            border: solid transparent;
            content: ' ';
            height: 0;
            bottom: 100%;
            position: absolute;
            width: 0;
          }
          &:after {
            border-width: 6px;
            border-bottom-color: #fff;
            left: 79px;
          }
          &:before {
            border-width: 8px;
            border-bottom-color: $listborderColor;
            left: 77px;
          }
          ul {
            .list {
              width: 106px;
              line-height: 40px;
              color: $listTitleColor;
              font-size: $fs14;
              border-bottom: 1px solid $listborderColor;
              .el-button--text {
                color: $listTitleColor;
              }
            }
          }
        }
      }
      .select {
        color: $borderColor !important;
        .icon {
          color: $borderColor !important;
        }
      }
    }

    .new-folder {
      margin: 30px 50px 10px;
      width: 120px;
      line-height: 40px;
      text-align: center;
      border-radius: 20px;
      border: 1px solid $listborderColor;
      color: $listTitleColor;
      cursor: pointer;
    }
    .new-name {
      position: relative;
      width: 182px;
      margin: 30px 19px;
      overflow: hidden;
      span {
        position: absolute;
        right: 10px;
        top: 12px;
        color: $vfConcentColor;
        font-size: $fs14;
        line-height: 20px;
      }
      .self-input {
        padding-right: 50px !important;
        width: 110px;
        color: $listTitleColor;
        font-size: $fs14;
      }
      .save-btn-two {
        float: left;
        color: $colorWhite;
      }
      .cancel-btn {
        float: right;
      }
      button {
        padding: 0px;
        margin-top: 10px;
        width: 80px;
        height: 40px;
        font-size: $fs14;
        border-color: $vfConcentColor;
        color: $listTitleColor;
      }
    }
    .takeup {
      position: absolute;
      bottom: 0px;
      margin: 0 auto;
      width: 100%;
      height: 70px;
      color: $listborderColor;
      background: $colorWhite;
      font-size: $fs12;
      line-height: 20px;
      text-align: center;
      cursor: pointer;
      span {
        display: inline-block;
        width: 40px;
        height: 40px;
        background: #F8F8F8;
        border: 1px solid $listborderColor;
        line-height: 40px;
        border-radius: 50%;
      }
    }
  }

  .new-name-modal {
    position: relative;
    width: 280px;
    margin: 0 auto;
    span {
      position: absolute;
      top: 10px;
      color: $listTitleColor;
      top: 10px;
      right: 20px;
    }
    .large-input {
      width: 210px !important;
    }
    .self-input {
      padding-right: 50px !important;
      width: 110px;
      font-size: $fs14;
    }
    .save-btn-two {
      margin-right: 15px;
    }
    button {
      margin-top: 10px;
      width: 80px;
      font-size: $fs14;
    }
  }
</style>
